package handlers;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;

import consultoria.commands.views.ConsultoriaObjectsView;


public class SelectAllHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
	 	final IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
		if (activePart instanceof ConsultoriaObjectsView) {
			ConsultoriaObjectsView activeView = (ConsultoriaObjectsView) activePart;
			activePart.getSite().getSelectionProvider().setSelection(new IStructuredSelection() {
				
				
				@Override
				public boolean isEmpty() {
					// TODO Auto-generated method stub
					return loadObjects().length == 0;
				}
				
				@Override
				public List toList() {
					return Arrays.asList(loadObjects());
				}
				
				@Override
				public Object[] toArray() {
					// TODO Auto-generated method stub
					return loadObjects();
				}
				
				@Override
				public int size() {
					// TODO Auto-generated method stub
					return loadObjects().length;
				}
				
				@Override
				public Iterator iterator() {
					// TODO Auto-generated method stub
					return Arrays.asList(loadObjects()).iterator();
				}
				
				@Override
				public Object getFirstElement() {
					// TODO Auto-generated method stub
					return loadObjects()[0];
				}
				
				public Object[] loadObjects() {
					StructuredViewer struViewer = (StructuredViewer)activePart.getSite().getSelectionProvider();
					return (Object[]) ((IStructuredContentProvider)struViewer.getContentProvider()).getElements(struViewer.getInput());
				}
			});
		}
		
		return null;
	}

}
